package com.bjpowernode.front.service.impl;

import com.bjpowernode.common.constants.RedisKey;
import com.bjpowernode.common.util.CommonUtil;
import com.bjpowernode.front.service.SmsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 注册发送短信验证码
 */
@Service(value = "smsLoginServiceImpl")
public class SmsLoginServiceImpl implements SmsService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean sendSms(String phone) {
        //验证手机号码
        if (CommonUtil.checkPhone(phone)){
            //设置短信内容
            String random = RandomStringUtils.randomNumeric(4);
            System.out.println("登录短信验证码是："+random);
            //验证码保存到redis
            stringRedisTemplate.opsForValue().set(RedisKey.KEY_SMS_LOGIN_PHONE+":"+phone,random,2, TimeUnit.MINUTES);
            return true;
        }
        return false;
    }

    @Override
    public boolean checkSmsCode(String phone, String code) {
        //验证手机号是否正确
        if (CommonUtil.checkPhone(phone)){
            //获取验证码
            String redisCode = stringRedisTemplate.opsForValue().get(RedisKey.KEY_SMS_LOGIN_PHONE + ":" + phone);
            if (redisCode != null){
                if (Objects.equals(code, redisCode)){
                    //验证码相同则返回true
                    return true;
                }else {
                    return false;
                }
            }
        }
        return false;
    }
}
